package com.cmj.runner;

import com.cmj.Utils.BeanCopyUtils;
import com.cmj.Utils.RedisCache;
import com.cmj.dao.ArticleMapper;
import com.cmj.domain.entity.Article;
import com.cmj.domain.vo.ArticleViewVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

import static com.cmj.domain.SystemConstants.ARTICLE_STATUS_NORMAL;

@Component
public class InitRunner implements CommandLineRunner {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void run(String... args) throws Exception {
        //获取文章的初始浏览量
        List<Article> articles = articleMapper.selArticleList(null, ARTICLE_STATUS_NORMAL);
        List<ArticleViewVo> arView = BeanCopyUtils.copyBeanList(articles, ArticleViewVo.class);
        //标记一个奇怪的问题，如果value是Long类型那么写入redis的时候会自动转换为String类型而不是ing类型
        //目前实力不够，不知道啥问题
        HashMap<String, Integer> hashMap = new HashMap<>();
        //hash中key值要是string
        BoundHashOperations viewKey = redisTemplate.boundHashOps("article:viewCount");
        for (ArticleViewVo view : arView) {
            hashMap.put(view.getId().toString(), view.getViewCount().intValue());
        }
        redisCache.setCacheMap("article:viewCount",hashMap);
        System.out.println("浏览量已经初始同步到redis");
    }
}